<template>
  <a-menu
    accordion
    :auto-open-selected="true"
    :level-indent="40"
    v-model:selected-keys="activeMenus"
    @menu-item-click="handleOnMenuItemClick"
  >
    <template v-for="menu in menuItems">
      <template v-if="menu">
        <a-sub-menu v-if="menu.children" :key="menu.label" :title="menu.label">
          <template v-if="menu.icon" #icon><guat-icon :icon="menu.icon" :size="24" /></template>
          <a-menu-item v-for="child in menu.children" :key="child?.key">
            {{ child?.label }}
          </a-menu-item>
        </a-sub-menu>
        <a-menu-item v-else :key="menu.key">
          <template v-if="menu.icon" #icon><guat-icon :icon="menu.icon" :size="24" /></template>
          {{ menu.label }}
        </a-menu-item>
      </template>
    </template>
  </a-menu>
</template>

<script setup lang="ts">
import useUserStore from "@/store/user";
import { RouteRecordRaw } from "vue-router";

interface MenuOption {
  key: string;
  label: string;
  icon?: string;
  children?: MenuOption[];
}

const router = useRouter();
const userStore = useUserStore();
const currentRoutes = computed(() => userStore.getAuthRoutes);
const activeMenus = ref(["/member"]);
const menuItems = computed<MenuOption[]>(() => {
  return currentRoutes.value.map((route) => createMenuItem("", route)) as MenuOption[];
});

const createMenuItem = (parentPath: string, route: RouteRecordRaw) => {
  if (route.meta?.hide) return undefined;
  const fullPath = `${parentPath}/${route.path}`;
  const menu: MenuOption = {
    key: fullPath,
    label: route.meta!.label as string,
  };

  if (route.meta?.icon) {
    menu.icon = route.meta.icon as string;
  }

  if (route.children && route.children.length > 0) {
    const _children = route.children.map((child) => createMenuItem(fullPath, child));
    const children = _children.filter((child) => child != undefined) as MenuOption[];
    menu.children = children;
  }

  return menu;
};

const handleOnMenuItemClick = (key: string) => {
  activeMenus.value = [key];
  if (router.currentRoute.value.fullPath != key) router.replace(key);
};

watch(
  () => router.currentRoute.value.fullPath,
  (val) => {
    activeMenus.value = [val];
  },
  {
    immediate: true,
  }
);

onMounted(() => menuItems.value);
</script>

<style scoped></style>
